package com.industrial.im.service.impl;

import cn.hutool.core.util.IdUtil;
import com.industrial.common.core.domain.R;
import com.industrial.common.security.utils.SecurityUtils;
import com.industrial.im.domain.ImGroupAdmin;
import com.industrial.im.domain.req.GroupReq;
import com.industrial.im.mapper.ImGroupAdminMapper;
import com.industrial.im.service.IMsgGroupInfoService;
import com.industrial.im.service.ImGroupService;
import com.industrial.system.api.RemoteUserService;
import com.industrial.system.api.domain.SysUser;
import io.rong.RongCloud;
import io.rong.methods.group.Group;
import io.rong.methods.user.User;
import io.rong.models.Result;
import io.rong.models.group.GroupMember;
import io.rong.models.group.GroupModel;
import io.rong.models.response.GroupUser;
import io.rong.models.response.GroupUserQueryResult;
import io.rong.models.response.UserGroupQueryResult;
import io.rong.models.user.UserModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 群组Service
 * </p>
 *
 * @author SangGuangCan
 */
@Service
public class ImGroupServiceImpl implements ImGroupService {

    @Autowired
    private RongCloud rongCloud;

    @Autowired
    private RemoteUserService remoteUserService;

    @Autowired
    private ImGroupAdminMapper imGroupAdminMapper;

    @Autowired
    private IMsgGroupInfoService msgGroupInfoService;

    /**
     * <p>
     * 创建群组
     * </p>
     *
     * @param groupReq
     * @return
     */
    @Override
    public Result createImGroup(GroupReq groupReq) {

        List<String> userIds = groupReq.getUserIds();
        if (userIds == null || userIds.isEmpty()) {
            throw new RuntimeException("请选择创建群组的成员");
        }
        //创建的同时需要把当前创建人也要加入这个群组
        String userId = SecurityUtils.getUserId();
        userIds.add(userId);
        List<GroupMember> groupMemberList = new ArrayList<>();
        for (String temp : userIds) {
            GroupMember tempGroupMember = new GroupMember();
            tempGroupMember.setId(temp);
            groupMemberList.add(tempGroupMember);
        }

        Group Group = rongCloud.group;

        GroupMember[] members = groupMemberList.toArray(new GroupMember[groupMemberList.size()]);


        String groupId = IdUtil.simpleUUID();
        GroupModel group = new GroupModel()
                .setId(groupId)
                .setMembers(members)
                .setName(groupReq.getGroupName());

        ImGroupAdmin imGroupAdmin = new ImGroupAdmin();
        imGroupAdmin.setBaseId(IdUtil.simpleUUID());
        imGroupAdmin.setUserId(userId);
        imGroupAdmin.setGroupId(groupId);
        imGroupAdminMapper.insert(imGroupAdmin);

        try {
            Result groupCreateResult = Group.create(group);
            msgGroupInfoService.saveGroupInfo(groupReq.getGroupName());
            return groupCreateResult;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * <p>
     * 查询用户所在的群组
     * </p>
     *
     * @return
     */
    @Override
    public UserGroupQueryResult queryUserInGroup(String userId) {

        User User = rongCloud.user;

        UserModel user = new UserModel().setId(userId);

        UserGroupQueryResult userGroupResult = null;
        try {
            userGroupResult = User.getGroups(user);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return userGroupResult;
    }

    /**
     * <p>
     * 查询群组内成员
     * </p>
     *
     * @param groupId
     * @return
     */
    @Override
    public List<SysUser> queryGroupMembers(String groupId) {
        Group Group = rongCloud.group;

        GroupModel group = new GroupModel();
        group.setId(groupId);
        try {
            GroupUserQueryResult getMemberesult = Group.get(group);
            List<GroupUser> members = getMemberesult.getMembers();
            List<SysUser> list = new ArrayList<>();
            if (members != null && !members.isEmpty()) {
                List<String> userIds = members.stream().map(GroupUser::getId).collect(Collectors.toList());
                R<List<SysUser>> userInfoListRes = remoteUserService.queryUserInfoByUserIds(userIds);
                if (userInfoListRes.getCode() == R.SUCCESS) {
                    List<SysUser> data = userInfoListRes.getData();
                    if (data != null && !data.isEmpty()) {
                        Map<String, String> userInfoMap = data.stream().collect(Collectors.toMap(SysUser::getUserId, SysUser::getNickName));
                        for (GroupUser p : members) {
                            String id = p.getId();
                            String nickName = userInfoMap.get(id);
                            SysUser tempUser = new SysUser();
                            tempUser.setUserId(id);
                            tempUser.setNickName(nickName);
                            list.add(tempUser);
                        }
                    }
                } else {
                    throw new RuntimeException("组内成员查询失败");
                }
            }
            return list;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * <p>
     * 解散群组
     * </p>
     *
     * @param params
     * @return
     */
    @Override
    public Result dissolveGroup(Map<String, String> params) {

        Group Group = rongCloud.group;
        String groupId = params.get("groupId");
        String userId = params.get("userId");

        int count = imGroupAdminMapper.selectUserGroupCount(groupId, userId);
        if (count == 0) {
            throw new RuntimeException("您没有删除该群组的权限");
        }

        GroupMember[] members = new GroupMember[]{new GroupMember().setId(userId)};

        GroupModel group = new GroupModel()
                .setId(groupId)
                .setMembers(members);

        try {
            Result groupDismissResult = (Result) Group.dismiss(group);
            return groupDismissResult;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * <p>
     * 邀请用户入群
     * </p>
     *
     * @param groupReq
     * @return
     */
    @Override
    public Result invitingUsersJoinGroup(GroupReq groupReq) {
        List<GroupMember> groupMemberList = new ArrayList<>();
        List<String> userIds = groupReq.getUserIds();
        for (String temp : userIds) {
            GroupMember tempGroupMember = new GroupMember();
            tempGroupMember.setId(temp);
            groupMemberList.add(tempGroupMember);
        }
        GroupMember[] members = groupMemberList.toArray(new GroupMember[groupMemberList.size()]);
        GroupModel group = new GroupModel()
                .setId(groupReq.getGroupId())
                .setMembers(members)
                .setName(groupReq.getGroupName());
        try {
            Result groupInviteResult = (Result) rongCloud.group.invite(group);
            return groupInviteResult;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * <p>
     * 移除群中的成员
     * </p>
     *
     * @param params userId 被移除的用户，groupId 群组Id
     * @return
     */
    @Override
    public Result removeGroupUser(Map<String, String> params) {

        GroupMember[] members = {new GroupMember().setId(params.get("userId"))};
        String groupId = params.get("groupId");
        String groupName = params.get("groupName");
        GroupModel group = new GroupModel()
                .setId(groupId)
                .setMembers(members);
        try {
            Result groupQuitResult = (Result) rongCloud.group.quit(group);
            return groupQuitResult;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
